package com.tianpengtech.common.pay.weixin;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.tianpengtech.common.model.fairorder.FairOrder;
import com.tianpengtech.common.pay.service.PayService;
import com.tianpengtech.common.pay.weixin.config.WXPayConfig;
import com.tianpengtech.common.pay.weixin.config.WXPayConfigImpl;
import com.tianpengtech.common.pay.weixin.required.WXPayRequest;
import com.tianpengtech.common.pay.weixin.required.WxPayUtil;
import com.tianpengtech.common.util.DateUtils;

public class WxPayParamBuilder {
	
	public final static String TRADETYPE_NATIVE="NATIVE";
	public final static String RETURN_CODE_SUCCESS="SUCCESS";
	public final static String RETURN_MSG_SUCCESS="OK";
	public final static String RETURN_CODE_FAIL="FAIL";
	
	public static String createWxPaySignWithNative(String name,String nonceStr,String outTradeNo ,String totalFee) throws Exception{
		Map<String, String> param = createWxPaySign(name,nonceStr,outTradeNo, totalFee,TRADETYPE_NATIVE);
        String sign = WxPayUtil.generateSignature(param,WXPayConfigImpl.getInstance().getKey());
		return sign;
	}
	
	private static Map<String,String> createWxPaySign(String name,String nonceStr,String outTradeNo ,String totalFee
			,String tradeType) throws Exception{
		
		WXPayConfig config = WXPayConfigImpl.getInstance();
		Map<String, String> param = new HashMap<String, String>();
		String appid=config.getAppID();
		String mch_id=config.getMchID();
		String notifyUrl = config.getNotifyUrl();
		String spbillCreateIp = config.getSpbillCreateIp();
		
        param.put("appid",appid);
        //商户号
        param.put("mch_id",mch_id);
        //随机字符串
        param.put("nonce_str", nonceStr);
        //商品描述
        param.put("body", name);
        //商户订单号
        param.put("out_trade_no",outTradeNo);
        //总金额
        param.put("total_fee",totalFee);
        //终端IP
        param.put("spbill_create_ip",spbillCreateIp);
        //回调地址
        param.put("notify_url",notifyUrl);
        //交易类型
        param.put("trade_type",tradeType);
        return param;
	}
	
	public static Map<String,Object> fetchNativeQrCode(String name,String nonceStr,String outTradeNo ,String totalFee,String sign,long userId) throws Exception{
		return fetchQrCode(name,nonceStr, outTradeNo, totalFee, TRADETYPE_NATIVE, sign,userId);
	}
	
	public static Map<String,Object> fetchNativeQrCode(String name,String nonceStr,String outTradeNo ,String totalFee,String sign,long userId,int objId,int opt_type) throws Exception{
		return fetchQrCode(name,nonceStr, outTradeNo, totalFee, TRADETYPE_NATIVE, sign,userId,objId,opt_type);
	}
	
	private static Map<String,Object> fetchQrCode(String name,String nonceStr,String outTradeNo ,String totalFee,String tradeType,String sign,long userId,int objId,int opt_type) throws Exception{
		String qrCodeUrl ="";
		WXPayConfig config = WXPayConfigImpl.getInstance();
		String appid=config.getAppID();
		String notifyUrl = config.getNotifyUrl();
		String spbillCreateIp = config.getSpbillCreateIp();
		String mch_id=config.getMchID();
		// 请求参数设定
        StringBuffer sb = new StringBuffer("<xml>");
        sb.append("<appid>").append(appid).append("</appid>");
        sb.append("<body>").append(name).append("</body>");
        sb.append("<mch_id>").append(mch_id).append("</mch_id>");
        sb.append("<nonce_str>").append(nonceStr).append("</nonce_str>");
        sb.append("<notify_url>").append(notifyUrl).append("</notify_url>");
        sb.append("<out_trade_no>").append(outTradeNo).append("</out_trade_no>");
        sb.append("<spbill_create_ip>").append(spbillCreateIp).append("</spbill_create_ip>");
        sb.append("<total_fee>").append(totalFee).append("</total_fee>");
        sb.append("<trade_type>").append(tradeType).append("</trade_type>");
        sb.append("<sign>").append(sign).append("</sign>");
        sb.append("</xml>");
		
        String url = "/pay/unifiedorder";
        String result = new WXPayRequest(WXPayConfigImpl.getInstance()).requestWithoutCert(url, WxPayUtil.generateUUID(), sb.toString(), false);
        
        
       
        Map<String, String> resultMap = WxPayUtil.xmlToMap(result);
        Map<String, Object> jsonMap = new HashMap<String,Object>();
       
        String return_code = resultMap.get("return_code");
        String result_code = resultMap.get("result_code");
        if(return_code.equals("SUCCESS") && result_code.equals("SUCCESS")){
        	PayService service = new PayService();
        	String sql="select * from fair_order where unique_id=? limit 1";
    		Record record = Db.findFirst(sql,outTradeNo);
    		if(record==null){
    			int id = service.saveOrder(result,resultMap,outTradeNo,userId,totalFee,name,objId,opt_type);
    			jsonMap.put("id",id);
    		}
        	qrCodeUrl =resultMap.get("code_url");
        	jsonMap.put("qrCodeUrl", qrCodeUrl);
        }
        return jsonMap;
	}
	
	
	private static Map<String,Object> fetchQrCode(String name,String nonceStr,String outTradeNo ,String totalFee,
			String tradeType,String sign,long userId) throws Exception{
		
		return fetchQrCode(name, nonceStr, outTradeNo, totalFee, tradeType, sign, userId,0,FairOrder.OPT_TYPE_CHARGE);
	}
	
	public  static String orderId(){
		return DateUtils.formateData(new Date(), "yyyyMMddHHmmssSS");
	}
	
	
	public  static String randomInt(){
		return DateUtils.formateData(new Date(), "HHmmssSS");
	}
	
	public static void builderMsgToWeixin(String return_code,String return_msg){
		StringBuffer sb = new StringBuffer();
		sb.append("<xml>")
		.append("<return_code><![CDATA["+return_code+"]]></return_code>")
		.append("<return_msg><![CDATA["+return_msg+"]]></return_msg>")
		.append("</xml>");
	}
	
	
	public static void main(String[] args) {
		System.out.println(randomInt());
	}
}
